package com.zmn.oms.dubbo.impl.zmn.order;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dto.ResponseDTO;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.common.utils.response.ResponseUtil;
import com.zmn.consts.GateTypeConsts;
import com.zmn.oms.business.interfaces.messageV1.app.MessageSendAppService;
import com.zmn.oms.business.interfaces.work.OrderWorkBService;
import com.zmn.oms.business.interfaces.work.OrderWorkListBService;
import com.zmn.oms.common.constant.ChannelConsts;
import com.zmn.oms.common.constant.MessageRuleIdConsts;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.constant.OrderStatusConsts;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.dubbo.dto.zmn.order.*;
import com.zmn.oms.dubbo.dto.zmn.order.factory.GateScheduleDIO;
import com.zmn.oms.dubbo.dto.zmn.serviceitem.OrderServiceItemDRO;
import com.zmn.oms.dubbo.utils.DubboConsts;
import com.zmn.oms.model.bo.order.OrderBO;
import com.zmn.oms.model.dto.order.OrderReworkDTO;
import com.zmn.oms.model.dto.order.zmn.ZsNormalNewOrderDTO;
import com.zmn.oms.model.dto.order.zmn.ZsNormalUpdateOrderDTO;
import com.zmn.oms.model.dto.product.OrderProductDTO;
import com.zmn.oms.model.dto.remark.OrderRemarkDetailDTO;
import com.zmn.oms.model.dto.work.masterwork.ModifyQuotationDTO;
import com.zmn.oms.model.dto.work.modify.CheckReworkOrderDTO;
import com.zmn.oms.model.dto.work.modify.must.ZsCancelDTO;
import com.zmn.oms.model.entity.detail.OrderDetail;
import com.zmn.oms.model.entity.master.OrderMaster;
import com.zmn.oms.model.entity.order.OrderExtend;
import com.zmn.oms.model.entity.product.OrderProduct;
import com.zmn.oms.model.entity.serviceitem.OrderServiceItem;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.base.oms.common.model.es.orderwork.EsOrderWork;
import com.zmn.base.oms.common.model.es.orderwork.EsOrderWorkOperate;
import com.zmn.oms.model.vo.work.ZsNormalUpdateOrderProductVO;
import com.zmn.oms.model.vo.work.ZsNormalUpdateOrderVO;
import com.zmn.oms.model.vo.work.detail.ZsOrderWorkDetailCommentVO;
import com.zmn.oms.model.vo.work.detail.ZsOrderWorkDetailContactVO;
import com.zmn.oms.model.vo.work.detail.ZsOrderWorkDetailVO;
import com.zmn.oms.model.vo.work.detail.ZsOrderWorkDetailWarrantyVO;
import com.zmn.oms.model.vo.work.modify.amount.ZsServiceItemVO;
import com.zmn.oms.model.vo.work.schedule.OrderScheduleVO;
import com.zmn.oms.model.vo.work.schedule.ScheduleDayVo;
import com.zmn.oms.services.interfaces.comment.OrderCommentService;
import com.zmn.oms.services.interfaces.detail.OrderDetailService;
import com.zmn.oms.services.interfaces.master.OrderMasterService;
import com.zmn.oms.services.interfaces.order.OrderExtendService;
import com.zmn.oms.services.interfaces.product.OrderProductService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.zmn.business.interfaces.work.OrderWorkModifyProductBService;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkBService;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkQueryBService;
import com.zmn.oms.zmn.business.interfaces.work.ZsOrderWorkScheduleBService;
import com.zmn.oms.zmn.business.interfaces.work.autoflow.WorkFlowContextBService;
import com.zmn.oms.zmn.normal.business.interfaces.order.ZsNormalOrderBService;
import com.zmn.oms.zmn.normal.business.interfaces.serviceitem.ZsNormalOrderServiceItemBService;
import com.zmn.oms.zmn.normal.business.interfaces.work.ZsNormalWorkBService;
import io.shardingsphere.api.HintManager;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * 类描述：订单 remote service
 *
 * @author liuying
 * @date 2018/11/07 15:10
 * @see OrderWorkBaseRemoteService
 */
@Deprecated
public abstract class OrderBaseRemoteService extends OrderListBaseRemoteService {

    static final String TAG = "啄木鸟-订单";

//    @Reference(version = com.zmn.mer.dubbo.utils.DubboConsts.INTERFACE_VERSION, check = false)
//    protected FactoryListRemoteService factoryListRemoteService;
    @Autowired
    protected OrderWorkListBService orderWorkListBService;
    @Autowired
    protected OrderCommentService orderCommentService;
    @Autowired
    protected OrderWorkService orderWorkService;
    @Autowired
    protected OrderWorkBService orderWorkBService;
    @Autowired
    protected ZsNormalWorkBService zsNormalWorkBService;
    @Autowired
    protected ZsNormalOrderBService zsNormalOrderBService;
    @Autowired
    protected OrderProductService orderProductService;
    @Autowired
    protected OrderMasterService orderMasterService;
    @Autowired
    protected OrderDetailService orderDetailService;
    @Autowired
    protected ZsOrderWorkQueryBService orderWorkQueryBService;
    @Autowired
    ZsOrderWorkScheduleBService zsOrderWorkScheduleBService;
    @Autowired
    protected ZsOrderWorkBService zsOrderWorkBService;
    @Autowired
    private WorkFlowContextBService workFlowContextBService;
    @Autowired
    protected ZsNormalOrderServiceItemBService zsNormalOrderServiceItemBService;
    @Autowired
    private OrderWorkModifyProductBService orderWorkModifyProductBService;
    @Autowired
    private OrderExtendService orderExtendService;
    @Autowired
    private MessageSendAppService messageSendAppService;

    protected Logger logger = LoggerFactory.getLogger(getClass());


    /**
     * 返修单检查
     *
     * @param checkReworkOrderDIO
     * @return
     */
    public ResponseDTO checkReworkOrder(CheckReworkOrderDIO checkReworkOrderDIO) {
        CheckReworkOrderDTO checkReworkOrderDTO = BeanMapper.map(checkReworkOrderDIO, CheckReworkOrderDTO.class);
        try {
            OrderReworkDTO orderReworkDTO = zsNormalOrderBService.checkReworkId(checkReworkOrderDTO);
            CheckReworkOrderDRO orderReworkDRO = BeanMapper.map(orderReworkDTO,CheckReworkOrderDRO.class);
            return ResponseUtil.responseSuccessData(orderReworkDRO);
        } catch (OmsBaseException e) {
            return ResponseUtil.responseFail(e.getMessage());
        }
    }

    /**
     * 获取订单详情
     *
     * @param orderId
     * @return
     */
    public ResponseDTO<OrderDetailDRO> findOrderDetail(Long orderId) {

        Objects.requireNonNull(orderId);

        logger.info("[{}] 商家渠道订单查询：{}", TAG, "orderId:" + orderId);

        OrderDetailDRO orderDetailDRO = new OrderDetailDRO();

        try (HintManager hintManager = HintManager.getInstance()) {
            hintManager.setMasterRouteOnly();

            ZsOrderWorkDetailVO orderWorkDetail = orderWorkQueryBService.findOrderWorkDetail(orderId, orderId);

            BeanMapper.copy(orderWorkDetail, orderDetailDRO);
            orderDetailDRO.setWorkId(orderId);
            orderDetailDRO.setOrderId(orderId);

            // 联系信息
            ZsOrderWorkDetailContactVO contactVO = orderWorkDetail.getContactVO();
            if (contactVO != null) {
                orderDetailDRO.setContact(BeanMapper.map(contactVO, OrderContactDRO.class));
            }

            //保修信息
            ZsOrderWorkDetailWarrantyVO warrantyVO = orderWorkDetail.getWarranty();
            if (warrantyVO != null) {
                orderDetailDRO.setWarranty(BeanMapper.map(warrantyVO, OrderDetailWarrantyDRO.class));
            }

            // 评价
            ZsOrderWorkDetailCommentVO commentVO = orderWorkDetail.getUserCommentVO();
            if (commentVO != null) {
                orderDetailDRO.setComment(BeanMapper.map(commentVO, OrderCommentDRO.class));
            }
        }

        return ResponseUtil.responseSuccess(orderDetailDRO, GlobalConsts.SUCCESS_MSG);
    }

    /**
     * 获取订单
     *
     * @param orderId
     * @return
     */
    public ResponseDTO<OrderDRO> getOrderById(Long orderId) {
        try {
            OrderWork orderWork = orderWorkService.findOrderWorkByKeySrcMaster(orderId, orderId);
            if (orderWork == null) {
                return ResponseUtil.responseFail("订单不存在");
            }

            OrderDRO orderDRO = this.getOrderDROByDb(orderWork);
            return ResponseUtil.responseSuccess(orderDRO, DubboConsts.OK);
        } catch (Exception e) {
            logger.error("[{}] 获取订单错误：{}", TAG, e);
            return ResponseUtil.responseFail(e.getMessage());
        }
    }

    /**
     * 取消订单
     *
     * @param cancelOrderDIO
     * @return
     */
    public ResponseDTO cancelOrder(CancelOrderDIO cancelOrderDIO) {
        try {
            ZsCancelDTO zsCancelDTO = new ZsCancelDTO();
            zsCancelDTO.setOrderId(cancelOrderDIO.getOrderId());
            zsCancelDTO.setWorkId(cancelOrderDIO.getWorkId());
            zsCancelDTO.setContent(cancelOrderDIO.getRemark());
            if (Objects.nonNull(cancelOrderDIO.getReasonMap()) && cancelOrderDIO.getReasonMap().size() > 0) {
                List<OrderRemarkDetailDTO> detailDTOList = Lists.newArrayList();
                cancelOrderDIO.getReasonMap().forEach((k,v) -> {
                    OrderRemarkDetailDTO dto = new OrderRemarkDetailDTO() ;
                    dto.setMapId(k);
                    dto.setMapName(v);
                    detailDTOList.add(dto);
                });
                zsCancelDTO.setDetailDTOList(detailDTOList);

            }
            // 操作人信息
            zsCancelDTO.setOperator(Optional.ofNullable(cancelOrderDIO.getOperator()).orElse(cancelOrderDIO.getUserName()));
            zsCancelDTO.setOperatorId(Optional.ofNullable(cancelOrderDIO.getOrderId()).orElse(cancelOrderDIO.getUserId()));
            zsCancelDTO.setOperatorType(Optional.ofNullable(cancelOrderDIO.getOperatorType()).orElse(GlobalConsts.OPERATE_USER_TYPE_FACTORY));

            zsNormalWorkBService.saveCancel(zsCancelDTO);
            return ResponseUtil.responseSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.responseFail(e.getMessage());
        }
    }

    /**
     * 修改订单
     *
     * @param updateOrderDTO
     * @return
     */
    public ResponseDTO<NewOrderDRO> updateOrder(ZsNormalUpdateOrderDTO updateOrderDTO) {
        try {
            zsNormalOrderBService.updateOrder(updateOrderDTO);
            return ResponseUtil.responseSuccess("OK");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("[{}] 订单保存错误：{}", TAG, e);
            return ResponseUtil.responseFail(e.getMessage());
        }
    }

    /**
     * 新增普通订单
     *
     * @param newOrderDTO
     * @return
     */
    public ResponseDTO<NewOrderDRO> addOrder(ZsNormalNewOrderDTO newOrderDTO) {
        try {

            // 返修单处理
            if (newOrderDTO.getReworkId() != null && newOrderDTO.getPlatWork() == null) {
                OrderWork reworkOrderWork = orderWorkService.findOrderWorkByKey(newOrderDTO.getReworkId(), newOrderDTO.getReworkId());
                if (reworkOrderWork == null) {
                    throw new OmsBaseException("返修单号不能为空");
                }
                newOrderDTO.setPlatWork(reworkOrderWork.getPlatWork());
                newOrderDTO.setOrderServiceItemList(null);
            }

            // 计价器订单，只支持一个产品
            if (Objects.equals(OrderConsts.SERVICE_ITEM_TYPE_FAULT, newOrderDTO.getServItemType())) {
                List<OrderProductDTO> products = newOrderDTO.getOrderProductList();
                if (products.size() > 1 || Optional.ofNullable(products.get(0).getNumber()).orElse(1) > 1) {
                    throw new OmsBaseException("计价器订单只支持一个产品");
                }
            }

            // 返修单若是微信公众号来的返修单，重新设置渠道--临时处理
            if (Objects.equals(newOrderDTO.getReceiveEntranceId(), GateTypeConsts.GATE_WECHAT_SITE) && Objects.equals(newOrderDTO.getType(), OrderConsts.ORDER_TYPE_REWORK)) {
                newOrderDTO.setChannelId(ChannelConsts.CHANNEL_ID_WECHAR_GZH);
            }

            OrderBO orderBO = zsNormalOrderBService.insertOrder(newOrderDTO);

            NewOrderDRO newOrderDRO = new NewOrderDRO();
            newOrderDRO.setWorkId(orderBO.getOrderWork().getWorkId());
            newOrderDRO.setOrderId(orderBO.getOrderWork().getOrderId());
            logger.info("[{}] 添加订单返回：{}", TAG, newOrderDRO);

            // 工单自动流转
            OrderWork orderWork = orderBO.getOrderWork();
            workFlowContextBService.asyncAutoFlow(orderWork.getOrderId(),orderWork.getWorkId());

            return ResponseUtil.responseSuccess(newOrderDRO, "OK");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            logger.error("[{}] 订单保存错误：{}", TAG, e);
            return ResponseUtil.responseFail(e.getMessage());
        }
    }

    /**
     * 修改产品/故障项
     * @param modifyQuotationDTO
     * @return
     */
    public ResponseDTO<Boolean> updateOrderProduct(ModifyQuotationDTO modifyQuotationDTO) {
        logger.debug("start更新产品----->[{}]", JSON.toJSONString(modifyQuotationDTO));
        try {
            zsOrderWorkBService.updateOrderQuotation(modifyQuotationDTO);

            OrderWork orderWork = orderWorkService.findOrderWorkByKey(modifyQuotationDTO.getOrderId(),
                    modifyQuotationDTO.getWorkId());

            Integer masterId = orderWork.getMasterId();
            // 给工程师发送消息
            if (Objects.equals(modifyQuotationDTO.getQuotationType(), GlobalConsts.OPERATE_USER_TYPE_USER) && masterId != null && modifyQuotationDTO.getQuotationId() != null) {
                // 计价器故障项报价push
                Map<String, Object> params = Maps.newHashMap();
                params.put("order_id", String.valueOf(orderWork.getOrderId()));
                params.put("workId", String.valueOf(orderWork.getWorkId()));
                messageSendAppService.pushAppMessageInfo(MessageRuleIdConsts.PUSH_MSG_RULEID_LDD_BONUS, JSON.toJSONString(params), orderWork);
            }
            return ResponseUtil.responseSuccess(true, "OK");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            logger.error("[{}] 修改产品/故障项错误：{}", TAG, e);
            return ResponseUtil.responseFail(e.getMessage());
        }
    }

    /**
     * 获取预约时间
     * @return
     */
    public ResponseDTO<OrderScheduleDayDRO> getScheduleDayList() {
        try{
            List<ScheduleDayVo> scheduleDayList = zsOrderWorkScheduleBService.getScheduleDayList();
            List<OrderScheduleDayDRO> list = BeanMapper.mapList(scheduleDayList, OrderScheduleDayDRO.class);
            return ResponseUtil.responseSuccess(list,"OK");
        }catch (Exception e){
            e.printStackTrace();
            logger.error("[{}] 获取预约时间错误：{}", TAG, e);
            return ResponseUtil.responseFail(e.getMessage());
        }

    }

    /**
     * 获取预约时间
     * @param scheDate
     * @return
     */
    public ResponseDTO<OrderScheduleTimeDRO> getScheduleTimes(String scheDate) {
        try{
            Objects.requireNonNull(scheDate, "预约日期不能为空");
            OrderScheduleVO scheduleTimes = zsOrderWorkScheduleBService.getScheduleTimes(scheDate, null);
            OrderScheduleTimeDRO scheduleTimeDRO = BeanMapper.map(scheduleTimes, OrderScheduleTimeDRO.class);
            return ResponseUtil.responseSuccessData(scheduleTimeDRO);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("[{}] 获取预约时间错误：{}", TAG, e);
            return ResponseUtil.responseFail(e.getMessage());
        }
    }

    /**
     * 获取预约时间--加过滤
     * @param gateScheduleDIO
     * @return
     */
    public ResponseDTO<OrderScheduleTimeDRO> getScheduleTimes(GateScheduleDIO gateScheduleDIO) {

        try{
            Objects.requireNonNull(gateScheduleDIO.getScheDate(), "预约日期不能为空");
            OrderScheduleVO scheduleTimes = zsOrderWorkScheduleBService.getScheduleTimes(gateScheduleDIO.getScheDate(), null);
            scheduleTimes.setTimes(zsOrderWorkScheduleBService.processScheduleTimes(gateScheduleDIO.getOrderId(), gateScheduleDIO.getPlat(), gateScheduleDIO.getGateType(), scheduleTimes.getTimes()));
            OrderScheduleTimeDRO scheduleTimeDRO = BeanMapper.map(scheduleTimes, OrderScheduleTimeDRO.class);
            return ResponseUtil.responseSuccessData(scheduleTimeDRO);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("[{}] 获取预约时间错误：{}", TAG, e);
            return ResponseUtil.responseFail(e.getMessage());
        }
    }

    /**
     * 订单转化
     *
     * @param orderWork
     * @return
     */
    protected OrderDRO getOrderDROByDb(OrderWork orderWork) {
        OrderDRO orderDRO = new OrderDRO();

        OrderDetail orderDetail = orderDetailService.findOrderDetailByKeySrcMaster(orderWork.getOrderId());

        orderDRO.setPlat(orderWork.getPlat());
        orderDRO.setPlatWork(orderWork.getPlatWork());
        orderDRO.setOrderId(orderWork.getOrderId());
        orderDRO.setWorkId(orderWork.getWorkId());
        orderDRO.setType(orderWork.getType());
        orderDRO.setBizType(orderWork.getBizType());
        orderDRO.setReworkId(orderWork.getReworkId());
        orderDRO.setDutyTime(orderWork.getDutyTime());
        orderDRO.setProvinceId(orderDetail.getProvinceId());
        orderDRO.setProvinceName(orderDetail.getProvinceName());
        orderDRO.setCountryId(orderDetail.getCountyId());
        orderDRO.setCountryName(orderDetail.getCountyName());
        orderDRO.setStreetId(orderDetail.getStreetId());
        orderDRO.setStreet(orderDetail.getStreet());
        orderDRO.setRemark(orderDetail.getRemark());
        orderDRO.setLatitude(orderDetail.getLatitude());
        orderDRO.setLongitude(orderDetail.getLongitude());
        orderDRO.setAddress(orderDetail.getAddress());

        orderDRO.setDiscountAmount(orderWork.getDiscountAmount());
        orderDRO.setCompleteTime(orderWork.getCompleteTime());
        orderDRO.setOriginalAmount(orderWork.getOriginalAmount());
        orderDRO.setPayStatus(orderWork.getPayStatus());
        orderDRO.setRefundTargetWorkId(orderWork.getRefundTargetWorkId());
        orderDRO.setCityId(orderWork.getCityId());
        orderDRO.setCityName(orderDetail.getCityName());
        orderDRO.setCategOneId(orderWork.getCategOneId());
        orderDRO.setCategId(orderWork.getCategId());
        orderDRO.setChannelId(orderWork.getChannelId());
        orderDRO.setChannelName(orderWork.getChannelName());
        orderDRO.setCompantyId(orderWork.getCompanyId());
        orderDRO.setCompanyId(orderWork.getCompanyId());
        orderDRO.setManageCompanyId(orderWork.getManageCompanyId());
        orderDRO.setUserId(orderWork.getUserId());
        orderDRO.setServCategId(orderWork.getServCategId());
        orderDRO.setUserGender(orderDetail.getGender());
        orderDRO.setUserName(orderDetail.getUserName());
        orderDRO.setUserPhone(orderDetail.getTelephone());
        orderDRO.setStatus(orderWork.getStatus());
        orderDRO.setResultStatus(orderWork.getResultStatus());
        orderDRO.setUserPhoneTwo(orderDetail.getTelephone2());
        orderDRO.setReciverId(orderWork.getReceiverId());
        orderDRO.setDistributeId(orderWork.getDistributerId());
        orderDRO.setTotalAmount(orderWork.getTotalAmount());

        orderDRO.setMasterId(orderWork.getMasterId());
        orderDRO.setMasterName(orderWork.getMasterName());
        orderDRO.setCategOneId(orderWork.getCategOneId());
        orderDRO.setShowCategOneId(orderWork.getShowCategOneId());
        orderDRO.setShowCategId(orderWork.getShowCategId());
        orderDRO.setDistributeTime(orderWork.getDistributeTime());
        orderDRO.setServItemType(orderWork.getServItemType());
        orderDRO.setServCategName(orderDetail.getServCategName());
        // 工单工程师
        List<OrderMaster> orderMasterList = orderMasterService.listMasterByOrderIdList(Lists.newArrayList(orderWork.getOrderId()));
        if (!CollectionUtils.isEmpty(orderMasterList)) {
            Optional<OrderMaster> orderMasterOptional = orderMasterList.stream().filter(e -> Objects.equals(e.getMasterId(), orderWork.getMasterId())).findFirst();
            if (orderMasterOptional.isPresent()) {
                orderDRO.setMasterPhone(orderMasterOptional.get().getMasterPhone());
            }
        }

        //师傅相片
        OrderExtend orderExtend = orderExtendService.findOrderExtendByOrderId(orderWork.getOrderId());
        if (Objects.nonNull(orderExtend)) {
            orderDRO.setMasterSrc(orderExtend.getMasterSrc());
            orderDRO.setDifficultRatioId(orderExtend.getDifficultRatioId());
        }

        // 订单产品
        List<OrderProduct> orderProductList = orderProductService.listOrderProductByOrderIdSrcMaster(orderWork.getOrderId());
        if (!CollectionUtils.isEmpty(orderProductList)) {
            Optional<OrderProduct> orderProductOptional = orderProductList.stream().filter(e -> Objects.equals(e.getProductId(), orderWork.getProductId())).findFirst();
            if (orderProductOptional.isPresent()) {
                orderDRO.setCategOneName(orderProductOptional.get().getCategOneName());
                orderDRO.setShowServCategName(orderProductOptional.get().getShowCategName());
                orderDRO.setShowCategOneName(orderProductOptional.get().getShowCategOneName());
                orderDRO.setShowCategName(orderProductOptional.get().getShowCategName());
            }

            List<OrderProductDRO> orderProductDROList = BeanMapper.mapList(orderProductList, OrderProductDRO.class);
            orderDRO.setProductList(orderProductDROList);
        }

        // 服务项信息
        try {
            List<ZsServiceItemVO> serviceItemVos = zsNormalOrderServiceItemBService.findServiceItemVo(orderWork.getOrderId(), orderWork.getWorkId());
            if (!CollectionUtils.isEmpty(serviceItemVos)) {
                List<OrderServiceItem> orderServiceItems = new LinkedList<>();
                for (ZsServiceItemVO obj : serviceItemVos) {
                    if (!CollectionUtils.isEmpty(obj.getServiceItemList())) {
                        orderServiceItems.addAll(obj.getServiceItemList());
                    }
                }
                List<OrderServiceItemDRO> orerServiceItemDRO = BeanMapper.mapList(orderServiceItems, OrderServiceItemDRO.class);
                orderDRO.setOrderServiceItemList(orerServiceItemDRO);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

        return orderDRO;
    }

    /**
     * 订单转化
     *
     * @param esOrderWork
     * @return
     */
    protected OrderDRO getOrderDRO(EsOrderWork esOrderWork) {
        OrderDRO orderDRO = new OrderDRO();

        orderDRO.setPlat(esOrderWork.getPlat());
        orderDRO.setPlatWork(esOrderWork.getPlatWork());
        orderDRO.setOrderId(esOrderWork.getOrderId());
        orderDRO.setWorkId(esOrderWork.getId());
        orderDRO.setType(esOrderWork.getType());
        orderDRO.setBizType(esOrderWork.getBizType());
        orderDRO.setReworkId(esOrderWork.getReworkId());
        orderDRO.setDutyTime(esOrderWork.getDutyTime());
        orderDRO.setProvinceId(esOrderWork.getProvinceId());
        orderDRO.setProvinceName(esOrderWork.getProvinceName());
        orderDRO.setCountryId(esOrderWork.getCountyId());
        orderDRO.setCountryName(esOrderWork.getCountyName());
        orderDRO.setStreet(esOrderWork.getContact().getStreet());
        orderDRO.setRemark(esOrderWork.getRemark());

        if (StringUtils.isNotBlank(esOrderWork.getContact().getLocation())) {
            String[] arr = esOrderWork.getContact().getLocation().split(",");
            orderDRO.setLatitude(Double.valueOf(arr[0]));
            orderDRO.setLongitude(Double.valueOf(arr[1]));
        }

        orderDRO.setAddress(esOrderWork.getContact().getAddress());
        orderDRO.setCityId(esOrderWork.getCityId());
        orderDRO.setCityName(esOrderWork.getCityName());
        orderDRO.setCategOneId(esOrderWork.getCategOneId());
        orderDRO.setCategId(esOrderWork.getCategTwoId());
        orderDRO.setChannelId(esOrderWork.getChannelId());
        orderDRO.setChannelName(esOrderWork.getChannelName());
        orderDRO.setCompantyId(esOrderWork.getCompanyId());
        orderDRO.setUserId(esOrderWork.getUserId());
        orderDRO.setServCategId(esOrderWork.getServCategId());
        orderDRO.setUserGender(esOrderWork.getContact().getGender());
        orderDRO.setUserName(esOrderWork.getContact().getUserName());
        orderDRO.setUserPhone(esOrderWork.getContact().getPhone()[0]);
        orderDRO.setStatus(esOrderWork.getStatus());
        orderDRO.setResultStatus(esOrderWork.getResultStatus());
        if (esOrderWork.getContact().getPhone().length > 1) {
            orderDRO.setUserPhoneTwo(esOrderWork.getContact().getPhone()[1]);
        }
        List<EsOrderWorkOperate> operateList = esOrderWork.getOperateList();
        try {
            for (EsOrderWorkOperate operate : operateList) {
                Integer operateType = operate.getOperateType();
                Long operateId = operate.getOperatorId();
                if (Objects.equals(operateType, OrderConsts.ORDER_OP_TYPE_INPUT)) {
                    orderDRO.setReciverId(operateId);
                }
                if (Objects.equals(operateType, OrderConsts.ORDER_OP_TYPE_DISTRIBUTE)) {
                    orderDRO.setDistributeId(operateId);
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        orderDRO.setMasterId(esOrderWork.getMasterId());
        orderDRO.setMasterName(esOrderWork.getMasterName());
        orderDRO.setMasterPhone(esOrderWork.getMasterPhone());
        orderDRO.setCategOneId(esOrderWork.getCategOneId());
        orderDRO.setCategOneName(esOrderWork.getCategOneName());

        List<OrderProductDRO> productList = Lists.newArrayList();
        esOrderWork.getProductList().forEach(product -> {
            OrderProductDRO orderProductDRO = new OrderProductDRO(product.getProductId(), product.getProductName(), product.getNumber());
            orderProductDRO.setProductUnit(product.getProductUnit());
            orderProductDRO.setBrandId(product.getBrandId());
            orderProductDRO.setBrandName(product.getBrandName());
            productList.add(orderProductDRO);
        });
        orderDRO.setProductList(productList);

        return orderDRO;
    }

    protected SimpleOrderDRO getSimpleOrderDRO(EsOrderWork esOrderWork) {
        SimpleOrderDRO orderDRO = new SimpleOrderDRO();

        orderDRO.setOrderId(esOrderWork.getOrderId());
        orderDRO.setWorkId(esOrderWork.getId());
        orderDRO.setType(esOrderWork.getType());
        orderDRO.setDutyTime(esOrderWork.getDutyTime());
        orderDRO.setChannelId(esOrderWork.getChannelId());
        orderDRO.setChannelName(esOrderWork.getChannelName());
        orderDRO.setTotalAmount(esOrderWork.getTotalAmount());
        orderDRO.setDiscountAmount(esOrderWork.getDiscountAmount());
        orderDRO.setPrepayAmount(esOrderWork.getPrepayAmount());
        orderDRO.setPayStatus(esOrderWork.getPayStatus());
        int orderStatus = OrderStatusConsts.getOrderStatus(esOrderWork.getStatus(), esOrderWork.getResultStatus());
        orderDRO.setStatus(orderStatus);
        if (esOrderWork.getCommentStatus() != null && Objects.equals(esOrderWork.getCommentStatus(), GlobalConsts.YES)) {
            orderDRO.setIsComment(true);
        } else {
            orderDRO.setIsComment(false);
        }
        List<OrderProductDRO> productList = Lists.newArrayList();
        esOrderWork.getProductList().forEach(product -> {
            OrderProductDRO orderProductDRO = new OrderProductDRO(product.getProductId(), product.getProductName(), product.getNumber());
            orderProductDRO.setShowProductId(product.getShowProductId());
            orderProductDRO.setShowProductName(product.getShowProductName());
            orderProductDRO.setShowProductUnit(product.getShowProductUnit());
            orderProductDRO.setProductUnit(product.getProductUnit());
            orderProductDRO.setBrandId(product.getBrandId());
            orderProductDRO.setBrandName(product.getBrandName());
            productList.add(orderProductDRO);
        });
        orderDRO.setProductList(productList);

        return orderDRO;
    }

    /**
     * 厂商id映射成渠道id
     *
     * @return
     */
    protected Integer getChannelIdByFcId(Integer factoryId) throws OmsBaseException {
        // 渠道ID
        throw new OmsBaseException("厂商服务已下线");
        /*com.zmn.common.dto2.ResponseDTO<FactoryDRO> responseDTO = factoryListRemoteService.getFactoryById(factoryId);

        if (responseDTO.getData() == null) {
            throw new OmsBaseException(responseDTO.getMessage());
        }
        return responseDTO.getData().getChannelId();*/
    }

    public ResponseDTO<UpdateOrderDRO> findOrderUpdateDetail(Long orderId) {
        Objects.requireNonNull(orderId);
        logger.info("[{}] 查询修改订单ID：{}", TAG, orderId);
        try {
            ZsNormalUpdateOrderVO zsNormalUpdateOrderVO = zsOrderWorkBService.findUpdateOrderWorkVO(orderId, orderId);
            UpdateOrderDRO updateOrderDRO = BeanMapper.map(zsNormalUpdateOrderVO, UpdateOrderDRO.class);
            //厂商单信息
            if (zsNormalUpdateOrderVO.getOrderFactory() != null) {
                OrderFactoryDRO orderFactoryDRO = updateOrderDRO.getOrderFactory();
                ZsNormalUpdateOrderProductVO productVO = zsNormalUpdateOrderVO.getOrderProductList().get(0);
                orderFactoryDRO.setFaultIdList(productVO.getFaultIdList());
                orderFactoryDRO.setRemark(productVO.getRemark());
            }
            return ResponseUtil.responseSuccess(updateOrderDRO, "OK");
        } catch (Exception ex) {
            ex.printStackTrace();
            logger.error("[{}] 查询修改订单详情错误：{}", TAG, ex);
            return ResponseUtil.responseFail(ex.getMessage());
        }
    }



}